#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/11/22  22:26
# @Author: 余浪人
# @email: yulangren520@gmail.com
import json
import os
from functools import wraps
from pathlib import Path
from jinja2.exceptions import TemplateNotFound
from flask import Blueprint, request, current_app, render_template, abort, url_for
from flask_themes2 import render_theme_template
from apps import get_sys_url
from apps.lib.cache_sys import current_theme, mysql_conf
from apps.lib.public import redis_

webapp_bp = Blueprint('webapp_bp', __name__)


def render_theme(template, **context):
    theme = current_theme()
    try:
        return render_theme_template(theme, f'web_template/{theme}/templates/{template}', **context)
    except TemplateNotFound as e:
        return '未检测到模板文件！'


def Authority(obj):
    @wraps(obj)
    def inner(*args, **kwargs):
        IP = request.remote_addr
        try:
            redis_2 = redis_(2)
            redis_3 = redis_(3)
            val = redis_2.get(IP)
        except:return abort(503,'The server is not configured correctly,Please configure correctly TL-CMS! If not clear configuration, can contact the developer QQ: 1368419640')
        if val:
            old = json.loads(val)
            if old['count'] == current_app.config['MAX_NUM']:
                res = redis_3.set(IP, json.dumps(IP), current_app.config['RESTRICT_TIME'] * 60)  # 冻结IP
                if res:redis_2.delete(IP)
                return render_template('error_template/error_403.html')
        if redis_3.get(IP): return render_template('error_template/error_403.html')
        redis_4 = redis_(4)
        if redis_4.hget('forbid_ip',IP): return render_template('error_template/error_403.html')
        redis_2.close()
        redis_3.close()
        redis_4.close()
        new = obj(*args, **kwargs)
        return new

    return inner


def before_request():
    setting = Path(os.path.join(get_sys_url(), 'apps/setting.json'))
    mysql = mysql_conf()
    if not current_app.config.get('SQLALCHEMY_DATABASE_URI','') and mysql:
        current_app.config.update({"SQLALCHEMY_DATABASE_URI": f"mysql+cymysql://{mysql.mysql_user}:{mysql.mysql_password}@{mysql.mysql_host}:{mysql.mysql_port}/{mysql.mysql_dbName}"})
    elif setting.exists() and (not current_app.config.get('SQLALCHEMY_DATABASE_URI','')):
        fp=setting.open('r',encoding='utf-8')
        conf = json.loads(fp.read())
        database = conf.get('database')
        db_host = database['db_host']
        db_name = database['db_name']
        db_port = database['db_port']
        db_pwd = database['db_pwd']
        db_user = database['db_user']
        current_app.config.update({"SQLALCHEMY_DATABASE_URI":f"mysql+cymysql://{db_user}:{db_pwd}@{db_host}:{db_port}/{db_name}"})
    elif request.path!=url_for('sys_bp.install') and (request.path!=url_for('sys_bp.db_connect',classify=1) and request.path!=url_for('sys_bp.db_connect',classify=2)) and not current_app.config.get('SQLALCHEMY_DATABASE_URI',''):
        return '连接数据库失败！请检查配置是否正确'
webapp_bp.before_request(before_request)
from apps.webapp import controller
